import $ from 'jquery'

var tools = {};

// 从地址栏获取参数(全部参数)
// 如果传入name则返回字符串
tools.getArg = function(name, url) {
    var oldAddress = url || decodeURI(window.location.href);
    var temp = oldAddress.split('?');
    var result = {};
    if (temp.length < 2) {
        return undefined;
    }
    var argStr = temp[1];
    if (undefined !== name) {

        // 先匹配在中间的情况
        var temp2 = argStr.match(name + "=(.*?)&");
        if (null !== temp2) {
            return temp2[1];
        }

        // 再匹配在结尾的情况
        temp2 = argStr.match(name + "=(.*?)$");
        if (null !== temp2) {
            return temp2[1];
        }
        // 什么都没匹配到
        return "";
    }

    var args = argStr.split('&');
    $.each(args, function(i, e) {
        var arg = e;
        if ("" === e) {
            return;
        }
        result[e.split("=")[0]] = e.split("=")[1];
    });
    return result;
};

// 检查手机号格式
tools.checkPhoneFormat = function(phone, rejectPrompt = "手机号格式不正确") {

  if(!phone || ""==phone ){
    return Promise.reject("请输入手机号");
  }

  return new Promise(function(resolve, reject) {
    // var isLegal = /^(0|86|17951)?(13[0-9]|14[0-9]|15[012356789]|16[0-9]|17[0-9]|18[0-9]|19[0-9])[0-9]{8}$/.test(phone)
    // isLegal
    if (phone.length == 11) {
      resolve()
    } else {
      return reject(rejectPrompt)
    }
  })
}


//参考链接http://www.w3school.com.cn/js/js_cookies.asp
//此函数用于设置cookie
tools.setCookie = function(c_name, value, expiredays) {
    var exdate = new Date()
    exdate.setDate(exdate.getDate() + expiredays)
    document.cookie = c_name + "=" + escape(value) +
        ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()) + ";path=/;";
};

//参考链接http://www.w3school.com.cn/js/js_cookies.asp
//此函数用于获取cookie
tools.getCookie = function(c_name) {
    if (document.cookie.length > 0) {
        let c_start = document.cookie.indexOf(c_name + "=")
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1
            let c_end = document.cookie.indexOf(";", c_start)
            if (c_end == -1) c_end = document.cookie.length
            return unescape(document.cookie.substring(c_start, c_end))
        }
    }
    return "";
};

export default tools 